<!DOCTYPE HTML>
<html lang="zh-CN">

<head><meta name="generator" content="Hexo 3.9.0">
    <!--Setting-->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta http-equiv="Cache-Control" content="no-transform">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta name="apple-mobile-web-app-capable" content="ydong博客">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    <meta name="browsermode" content="application">
    <meta name="screen-orientation" content="portrait">
    <meta name="theme-version" content="1.2.3">
    <meta name="root" content="/blog/">
    <link rel="dns-prefetch" href="http://ydongabc.gitee.io/blog">
    <!--SEO-->

<meta name="keywords" content="promise,异步执行">


<meta name="description" content="1.基础要点
Promise 对象是一个 构造函数，可以  new Promise() 得到一个 Promise 的实例。
Promise 表示一个 异步操作；每当我们 new 一个 Promi...">


<meta name="robots" content="all">
<meta name="google" content="all">
<meta name="googlebot" content="all">
<meta name="verify" content="all">
    <!--Title-->

<title>
    
    使用Promise实现异步执行并解决回调地狱 |
    
    ydong博客
</title>

<link rel="alternate" href="/atom.xml" title="ydong博客" type="application/atom+xml">


<link rel="icon" href="./favicon.ico">

    

<link rel="stylesheet" href="/blog/css/bootstrap.min.css?rev=3.3.7">
<link rel="stylesheet" href="/blog/css/font-awesome.min.css?rev=4.7.0">
<link rel="stylesheet" href="/blog/css/style.css?rev=@@hash">
    
<div class="hide">
    <script type="text/javascript">
    var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");
    document.write(unescape("%3Cspan class='cnzz_stat_icon_1263868967 hide' %3E%3Cscript%20src%3D%22https%3A%2F%2Fs95.cnzz.com%2Fz_stat.php%3Fweb_id%3D1272564536%22%3E%3C%2Fscript%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s19.cnzz.com/z_stat.php%3Fid%3D1263868967%26show%3Dpic1' type='text/javascript'%3E%3C/script%3E"));
    </script>
</div>




    

</head></html>
<!--[if lte IE 8]>
<style>
    html{ font-size: 1em }
</style>
<![endif]-->
<!--[if lte IE 9]>
<div style="ie">你使用的浏览器版本过低，为了你更好的阅读体验，请更新浏览器的版本或者使用其他现代浏览器，比如Chrome、Firefox、Safari等。</div>
<![endif]-->
<body>
    <header class="main-header"  style="background-image:url(
    /blog/./img/banner.jpg)"
     >
    <div class="main-header-box">
        <a class="header-avatar" href="/" title='John Doe'>
            <img src="/blog/img/avatar.jpg" alt="logo头像" class="img-responsive center-block">
        </a>
        <div class="branding">
            <!--<h2 class="text-hide">Snippet主题,从未如此简单有趣</h2>-->
            
            <img src="/blog/img/branding.png" alt="Snippet 博客主题" class="img-responsive center-block">
            
        </div>
    </div>
</header>
    <nav class="main-navigation">
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="navbar-header"><span class="nav-toggle-button collapsed pull-right" data-toggle="collapse" data-target="#main-menu" id="mnav">
                        <span class="sr-only"></span>
                        <i class="fa fa-bars"></i>
                    </span>
                    <a class="navbar-brand" href="http://ydongabc.gitee.io/blog">
                        ydong博客</a>
                </div>
                <div class="collapse navbar-collapse" id="main-menu">
                    <ul class="menu">
                        
                        <li role="presentation" class="text-center">
                            <a href="/blog"><i class="fa "></i>
                                首页</a>
                        </li>
                        
                        <li role="presentation" class="text-center">
                            <a href="/blog/categories/前端/"><i class="fa "></i>
                                前端</a>
                        </li>
                        
                        <li role="presentation" class="text-center">
                            <a href="/blog/categories/后端/"><i class="fa "></i>
                                后端</a>
                        </li>
                        
                        <li role="presentation" class="text-center">
                            <a href="/blog/categories/工具/"><i class="fa "></i>
                                工具</a>
                        </li>
                        
                        <li role="presentation" class="text-center">
                            <a href="/blog/archives/"><i class="fa "></i>
                                时间轴</a>
                        </li>
                        
                    </ul>
                </div>
            </div>
        </div>
    </div>
</nav>
    <section class="content-wrap">
        <div class="container">
            <div class="row">
                <main class="col-md-8 main-content m-post">
                    <p id="process"></p>
<article class="post">
    <div class="post-head">
        <h1 id="使用Promise实现异步执行并解决回调地狱">
            
            使用Promise实现异步执行并解决回调地狱
            
        </h1>
        <div class="post-meta">
    
    <span class="categories-meta fa-wrap">
        <i class="fa fa-folder-open-o"></i>
        <a class="category-link" href="/blog/categories/前端/">前端</a> <a class="category-link" href="/blog/categories/前端/javascript/">javascript</a>
    </span>
    
    
    <span class="fa-wrap">
        <i class="fa fa-tags"></i>
        <span class="tags-meta">
            
            <a class="tag-link" href="/blog/tags/promise/">promise</a> <a class="tag-link" href="/blog/tags/异步执行/">异步执行</a>
            
        </span>
    </span>
    
    
    
    <span class="fa-wrap">
        <i class="fa fa-clock-o"></i>
        <span class="date-meta">
            2019/11/24</span>
    </span>
    
    
</div>
        
        
    </div>
    
    <div class="post-body post-content">
        <h2 id="1-基础要点"><a href="#1-基础要点" class="headerlink" title="1.基础要点"></a>1.基础要点</h2><ul>
<li>Promise 对象是一个 构造函数，可以  new Promise() 得到一个 Promise 的实例。</li>
<li>Promise 表示一个 异步操作；每当我们 new 一个 Promise 的实例，这个实例，就表示一个具体的异步操作。</li>
<li>Promise 上，有两个函数，分别叫做 resolve（成功之后的回调函数） 和 reject（失败之后的回调函数）。</li>
<li>在 Promise 构造函数的 Prototype 属性上，有一个 .then() 方法，只要是 Promise 构造函数创建的实例，都可以访问到 .then() 方法。</li>
<li>由于 Promise 的实例是一个异步操作，所以，内部拿到 操作的结果后，无法使用 return 把操作的结果返回给调用者； 这时候，只能使用回调函数的形式，来把成功或失败的结果，返回给调用者。</li>
<li>xxx.then(a =&gt; a) 的效果实际上是 return new Promise(resolve =&gt; resolve(a))。</li>
<li>then()方法的参数是两个回调函数，第一个是成功的回调，第二个是失败的回调，失败的回调函数可省略不写。</li>
<li>如上个then()中有代码执行失败报错，则会调用下一个then()中的失败回调函数处理，函数可接收传来的报错信息,如then()中没有失败的回调函数处理，可使用catch()方法接收处理。</li>
</ul>
<h2 id="2-用法详情"><a href="#2-用法详情" class="headerlink" title="2.用法详情"></a>2.用法详情</h2><h3 id="1-Promise的异步执行"><a href="#1-Promise的异步执行" class="headerlink" title="1.Promise的异步执行"></a>1.Promise的异步执行</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">demo</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> promise = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"异步代码执行成功"</span>);</span><br><span class="line">        <span class="keyword">if</span> (<span class="literal">false</span>) reject(); <span class="comment">//如果失败则执行失败回调函数</span></span><br><span class="line">        resolve();  <span class="comment">//成功则执行成功回调函数</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .then(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"成功1"</span>);</span><br><span class="line">    &#125;, () =&gt; &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"失败1"</span>);</span><br><span class="line">    &#125;)</span><br><span class="line">    .then(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"成功2"</span>) <span class="comment">//因为是异步的,此条因定时器延时，将在最后打印出来</span></span><br><span class="line">        &#125;, <span class="number">1000</span>);</span><br><span class="line">        <span class="built_in">console</span>.log(aaa); <span class="comment">// aaa未定义，此条将执行失败</span></span><br><span class="line">    &#125;)</span><br><span class="line">    .then(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"成功3"</span>);</span><br><span class="line">    &#125;, err =&gt; &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"失败3"</span> + err);</span><br><span class="line">    &#125;)</span><br><span class="line">    .catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"catch捕获"</span> + err);</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line">demo(); </span><br><span class="line"><span class="comment">// ---输出顺序结果如下:---</span></span><br><span class="line"><span class="comment">// 异步代码执行成功</span></span><br><span class="line"><span class="comment">// 成功1</span></span><br><span class="line"><span class="comment">// 失败3 ReferenceError: aaa is not defined</span></span><br><span class="line"><span class="comment">// 成功2</span></span><br></pre></td></tr></table></figure>

<h3 id="2-常规用法-后续的Promise执行，依赖于前面Promise执行的结果，并解决回调地狱"><a href="#2-常规用法-后续的Promise执行，依赖于前面Promise执行的结果，并解决回调地狱" class="headerlink" title="2.常规用法 (后续的Promise执行，依赖于前面Promise执行的结果，并解决回调地狱)"></a>2.常规用法 (后续的Promise执行，依赖于前面Promise执行的结果，并解决回调地狱)</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">demo2</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">console</span>.log(str + <span class="string">"执行成功"</span>)</span><br><span class="line">        resolve(str);  </span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">demo2(<span class="string">"第一次"</span>)</span><br><span class="line">.then(<span class="function"><span class="params">str</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log( str + <span class="string">"成功1"</span>);</span><br><span class="line">    <span class="comment">// console.log(aaa); // 此条会报错，将终止下面的Promise执行，并被catch()捕获</span></span><br><span class="line">    <span class="keyword">return</span> demo2(<span class="string">"第二次"</span>)</span><br><span class="line">&#125;)</span><br><span class="line">.then(<span class="function"><span class="params">str</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(str + <span class="string">"成功2"</span>);</span><br><span class="line">    <span class="keyword">return</span> demo2(<span class="string">"第三次"</span>)</span><br><span class="line">&#125;)</span><br><span class="line">.then(<span class="function"><span class="params">str</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(str + <span class="string">"成功3"</span>);</span><br><span class="line">&#125;)</span><br><span class="line">.catch(<span class="function"><span class="params">err</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(err);</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// ---输出顺序结果如下:---</span></span><br><span class="line"><span class="comment">// 第一次执行成功</span></span><br><span class="line"><span class="comment">// 第一次成功1</span></span><br><span class="line"><span class="comment">// 第二次执行成功</span></span><br><span class="line"><span class="comment">// 第二次成功2</span></span><br><span class="line"><span class="comment">// 第三次执行成功</span></span><br><span class="line"><span class="comment">// 第三次成功3</span></span><br></pre></td></tr></table></figure>

<p>如需当前面的Promise执行失败，让后续的Promise仍继续执行，可以为每个promise指定失败的回调，<br>即在then()中添加失败回调函数，并在该函数内添加 return demo2(“第二次”) 即可</p>

    </div>
    
    <div class="post-footer">
        <div>
            
            转载声明：
            商业转载请联系作者获得授权,非商业转载请注明出处 © <a href="" target="_blank">Snippet</a>
            
            
        </div>
        <div>
            
        </div>
    </div>
</article>
<div class="article-nav prev-next-wrap clearfix">
    
    <a href="/blog/2019/11/24/表格分页展示+搜索功能/" class="pre-post btn btn-default" title='表格分页展示+搜索功能'>
        <i class="fa fa-angle-left fa-fw"></i><span class="hidden-lg">上一篇</span>
        <span class="hidden-xs">
            表格分页展示+搜索功能</span>
    </a>
    
    
    <a href="/blog/2019/11/07/H5全屏滚动活动页插件/" class="next-post btn btn-default" title='H5全屏滚动活动页插件'>
        <span class="hidden-lg">下一篇</span>
        <span class="hidden-xs">
            H5全屏滚动活动页插件</span><i class="fa fa-angle-right fa-fw"></i>
    </a>
    
</div>

                </main>
                
                    <aside id="article-toc" role="navigation" class="col-md-4">
    <div class="widget">
        <h3 class="title">
            文章目录
        </h3>
        
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-基础要点"><span class="toc-text">1.基础要点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-用法详情"><span class="toc-text">2.用法详情</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-Promise的异步执行"><span class="toc-text">1.Promise的异步执行</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-常规用法-后续的Promise执行，依赖于前面Promise执行的结果，并解决回调地狱"><span class="toc-text">2.常规用法 (后续的Promise执行，依赖于前面Promise执行的结果，并解决回调地狱)</span></a></li></ol></li></ol>
        
    </div>
</aside>
                
            </div>
        </div>
    </section>
    <footer class="main-footer">
    <div class="container">
        <div class="row">
        </div>
    </div>
</footer>
<a id="back-to-top" class="icon-btn hide">
    <i class="fa fa-chevron-up"></i>
</a>
    <div class="copyright">
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="busuanzi">
    
</div>
            </div>
            <div class="col-sm-12">
                <span>Copyright &copy;
                    2017
                </span> |
                <span>
                    Powered by <a href="//hexo.io" class="copyright-links" target="_blank" rel="nofollow">Hexo</a>
                </span> |
                <span>
                    Theme by <a href="//github.com/shenliyang/hexo-theme-snippet.git" class="copyright-links" target="_blank" rel="nofollow">Snippet</a>
                </span>
            </div>
        </div>
    </div>
</div>



<script src="/blog/js/app.js?rev=@@hash"></script>
</body>
</html>